package com.atguigu.system.controller;

import com.atguigu.common.result.Result;
import com.atguigu.common.result.ResultCodeEnum;
import com.atguigu.common.util.MD5;
import com.atguigu.model.system.SysUser;
import com.atguigu.model.vo.LoginVo;
import com.atguigu.system.execption.GuiguException;
import com.atguigu.system.service.SysUserService;
import com.sun.net.httpserver.HttpServer;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 后台登录登出
 * </p>
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    SysUserService sysUserService;

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        // 1、登录验证，到数据库查看用户信息
        SysUser sysUser = sysUserService.getSysUserByUsername(loginVo.getUsername());
        // 2、查询用户是否存在
        if (sysUser == null){
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        // 3、密码是否正确
        if (!sysUser.getPassword().equals(MD5.encrypt(loginVo.getPassword()))){
            throw new GuiguException(ResultCodeEnum.PASSWORD_ERROR);
        }
        // 4、账户是否被禁用
        if (sysUser.getStatus() == 0){
            throw new GuiguException(ResultCodeEnum.ILLEGAL_REQUEST);
        }

        String token = UUID.randomUUID().toString().replaceAll("-","");
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        redisTemplate.boundValueOps(token).set(sysUser,30,TimeUnit.MINUTES);
        return Result.ok(map);
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {

        String token = request.getHeader("token");
        SysUser sysUser =(SysUser) redisTemplate.boundValueOps(token).get();
        if (sysUser == null){
            throw new GuiguException(ResultCodeEnum.ARGUMENT_VALID_ERROR);
        }
        Map<String,Object> map = sysUserService.getInfo(sysUser.getId());
        return Result.ok(map);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        redisTemplate.delete(token);
        return Result.ok();
    }

}
